package org.stayfool.nio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.time.LocalDateTime;

import org.junit.Test;
import org.stayfool.nio.enums.FileAccess;
import org.stayfool.nio.util.FileUtil;

/**
 * 文件随机读取，指定位置写入测试
 * 
 * @author SHYL
 *
 */
public class RandomFileReadAndWrite {

	String filepath = "random-file.txt";

	@Test
	public void randomWrite() {
		try {

			File f = new File(filepath);
			if (f.exists())
				f.delete();

			RandomAccessFile rf = new RandomAccessFile(f, FileAccess.READ_AND_WRITE.code());
			rf.writeBytes("[step 1] hello world \n");
			FileUtil.show(filepath);

			insertFileContent(30, "[step 2] Add after hello world \n", rf);
			FileUtil.show(filepath);

			rf.seek(rf.length());
			rf.writeBytes("[step 3] current system time : " + LocalDateTime.now().toString() + "\n");

			rf.close();

			FileUtil.show(filepath);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 指定位置插入
	private void insertFileContent(int index, String content, RandomAccessFile file) {
		try {
			// 计算新的文件长度
			long fileLength = file.length();
			long newLength = (index > fileLength ? index : fileLength) + content.length();
			file.setLength(newLength);

			// 向后移动文件插入位置的内荣
			byte tmp;
			if (index < fileLength) {
				long sum = fileLength - index;
				for (int i = 1; i <= sum; i++) {
					file.seek(fileLength - i);
					tmp = file.readByte();
					file.seek(newLength - i);
					file.write(tmp);
				}
			}
			// 填充空格,32为空格的asc码
			if (index > fileLength) {
				for (long i = fileLength; i < index; i++) {
					file.seek(i);
					file.write(32);
				}
			}

			file.seek(index);
			file.writeBytes(content);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
